// EventBus.ts
import { _decorator, Node } from 'cc';
const { ccclass } = _decorator;

type Callback = (...args: any[]) => void;


export enum TYPE  {
    SUN_CHANGE = 'SUN_CHANGE', // 太阳数量发生改变，新增或者消费
    PLANT_DRAGG_END = 'PLANT_DRAGG_END', // 植物拖拽后松手，开始种植
    PLANTING_SUCCESS = 'PLANTING_SUCCESS', // 植物种植成功
    ZOMBIE_DEATH = 'ZOMBIE_DEATH', // 僵尸死亡
    UPDATE_ZM_X = 'UPDATE_ZM_X' , // 更新僵尸位置

    DEBUG_ZOMBIE_RUN = 'DEBUG_ZOMBIE_RUN', // 调试僵尸行走
    DEBUG_ZOMBIE_EAT = 'DEBUG_ZOMBIE_EAT', // 调试僵尸吃
    DEBUG_ZOMBIE_DYING = 'DEBUG_ZOMBIE_DYING', // 调试僵尸半死亡
    DEBUG_ZOMBIE_DIE = 'DEBUG_ZOMBIE_DIE', // 调试僵尸死亡
}

@ccclass('EventBus')
export class EventBus {
    private static listeners: Map<string, Callback[]> = new Map();

    // 订阅
    public static on(event: string, callback: Callback) {
        if (!this.listeners.has(event)) {
            this.listeners.set(event, []);
        }
        this.listeners.get(event)!.push(callback);
    }


    public static once(event:string,callback:Callback) {
        const wrapper = (...args:any[])=>{
            callback(...args)
            this.off(event,wrapper)
        }
        this.on(event,wrapper)
    }

    // 取消订阅
    public static off(event: string, callback: Callback) {
        if (!this.listeners.has(event)) return;
        const arr = this.listeners.get(event)!;
        const index = arr.indexOf(callback);
        if (index !== -1) arr.splice(index, 1);
    }

    // 派发事件
    public static emit(event: string, ...args: any[]) {
        if (!this.listeners.has(event)) return;
        const arr = this.listeners.get(event)!;
        arr.forEach(cb => cb(...args));
    }
}
